package com.yumingjiang.weichatgtp.intercepter;

import com.yumingjiang.commontool.util.HttpClientResult;
import com.yumingjiang.commontool.util.LoggerUtil;
import com.yumingjiang.commontool.util.StringUtil;
import com.yumingjiang.weichatgtp.common.eunms.SystemResultStutasEnum;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * [一句话描述该类的功能]
 *
 * @author : [Administrator]
 * @version : [v1.0]
 * @createTime : [2023/3/11 23:56]
 */
public class ChatGPTParamsAndLogIntercepter implements MethodInterceptor {
    private final Logger LOGGER = LoggerFactory.getLogger(ChatGPTParamsAndLogIntercepter.class);

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {

        Method method = invocation.getMethod();
        //获得类名
        String className = method.getDeclaringClass().getSimpleName();
        //获得方法名
        String name = method.getName();
        //访问参数
        Object[] arguments = invocation.getArguments();
        String question = (String) arguments[0];

        HttpClientResult httpClientResult = new HttpClientResult();
        long startTime = System.currentTimeMillis();
        try {
            if (!StringUtil.batchIsNotBlank(question)) {
                httpClientResult.setSuccess(false);
                httpClientResult.setCode(SystemResultStutasEnum.LOSE_PARAMS.getCode());
                httpClientResult.setMessage(SystemResultStutasEnum.LOSE_PARAMS.getMessage());
                return httpClientResult;
            }
            httpClientResult = (HttpClientResult) invocation.proceed();
            return httpClientResult;
        } catch (Exception e) {
            LoggerUtil.error(LOGGER,e,this.getClass().getSimpleName() + " : "+SystemResultStutasEnum.SYSTEM_EXCEPTION.getMessage());
            httpClientResult.setSuccess(false);
            httpClientResult.setCode(SystemResultStutasEnum.SYSTEM_EXCEPTION.getCode());
            httpClientResult.setMessage(SystemResultStutasEnum.SYSTEM_EXCEPTION.getMessage());
            return httpClientResult;
        } finally {
            long endTime = System.currentTimeMillis();
            LoggerUtil.info(LOGGER, className,name, question , String.valueOf(endTime - startTime),
                    httpClientResult.isSuccess() ? "Y" : "N",String.valueOf(httpClientResult.getCode()),httpClientResult.getMessage());
        }
    }

}
